package com.lisn.mylib;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.navigation.NavController;
import androidx.navigation.fragment.NavHostFragment;
import androidx.navigation.ui.NavigationUI;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.lisn.commonlib.LiveDataBus;
import com.lisn.mylib.model.Destination;
import com.lisn.mylib.ui.activity.LiveDataBusTestActivity;
import com.lisn.mylib.utils.AppConfig;
import com.lisn.mylib.navigator.NavGraphBuilder;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import static com.google.android.material.bottomnavigation.BottomNavigationView.*;

public class MainActivity extends AppCompatActivity implements OnNavigationItemSelectedListener {

    private static final String TAG = MainActivity.class.getSimpleName();

    private OnNavigationItemSelectedListener navItemSelectedListener = new OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            int itemId = item.getItemId();
            Log.e(TAG, "onNavigationItemSelected: itemId = " + itemId);
            Log.e(TAG, "onNavigationItemSelected: itemId = " + item.getTitle());
            Log.e(TAG, "onNavigationItemSelected: itemId.toString = " + item.toString());
            if (tvTitle != null) {
                tvTitle.setText(item.getTitle());
            }
            if (navController != null) {
                return NavigationUI.onNavDestinationSelected(item, navController);
            }
            return false;
        }
    };
    private NavController navController;
    private TextView tvTitle;
    private BottomNavigationView navView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initActionBar();
        navView = findViewById(R.id.nav_view);
        Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment);
        navController = NavHostFragment.findNavController(fragment);
        NavGraphBuilder.build(this, navController, fragment.getId());
        Log.e(TAG,"onCreate: R.id.nav_host_fragment = "+R.id.nav_host_fragment);
        Log.e(TAG,"onCreate: fragment.getId = "+fragment.getId());

        navView.setOnNavigationItemSelectedListener(this);

        LiveDataBus.get().with(LiveDataBusTestActivity.EVENT_POST_STICKY_DATA)
                .observerSticky(this, new Observer() {
                    @Override
                    public void onChanged(Object o) {
                        Log.e(TAG, "onChanged: " + o.toString());
                    }
                }, true);

        LiveDataBus.get().with(LiveDataBusTestActivity.EVENT_POST_VALUE)
                .observe(this, new Observer() {
                    @Override
                    public void onChanged(Object o) {
                        Log.e(TAG, "onChanged: " + o.toString());
                    }
                });
    }

    /**
     * 自定义布局ActionBar（标题居中）
     */
    @SuppressLint("WrongConstant")
    private void initActionBar() {
        ActionBar.LayoutParams lp = new ActionBar.LayoutParams(
                ActionBar.LayoutParams.MATCH_PARENT,
                ActionBar.LayoutParams.MATCH_PARENT,
                Gravity.CENTER);
        View viewTitleBar = getLayoutInflater().inflate(R.layout.action_bar_title, null);
        getSupportActionBar().setCustomView(viewTitleBar, lp);
        getSupportActionBar().setDisplayShowHomeEnabled(false);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        getSupportActionBar().setDisplayShowCustomEnabled(true);
        tvTitle = (TextView) getSupportActionBar().getCustomView().findViewById(android.R.id.title);
    }


    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
        HashMap<String, Destination> destConfig = AppConfig.getDestConfig();
        Iterator<Map.Entry<String, Destination>> iterator = destConfig.entrySet().iterator();
        //遍历 target destination 是否需要登录拦截
//        while (iterator.hasNext()) {
//            Map.Entry<String, Destination> entry = iterator.next();
//            Destination value = entry.getValue();
//            if (value != null && !UserManager.get().isLogin() && value.needLogin && value.id == menuItem.getItemId()) {
//                UserManager.get().login(this).observe(this, new Observer<User>() {
//                    @Override
//                    public void onChanged(User user) {
//                        navView.setSelectedItemId(menuItem.getItemId());
//                    }
//                });
//                return false;
//            }
//        }

        navController.navigate(menuItem.getItemId());
        return !TextUtils.isEmpty(menuItem.getTitle());
    }

    @Override
    public void onBackPressed() {

        int currentPageId = navController.getCurrentDestination().getId();

        //APP页面路导航结构图  首页的destinationId
        int homeDestId = navController.getGraph().getStartDestination();

        //如果当前正在显示的页面不是首页，而我们点击了返回键，则拦截。
        if (currentPageId != homeDestId) {
            navView.setSelectedItemId(homeDestId);
            return;
        }

        //否则 finish，此处不宜调用onBackPressed。因为navigation会操作回退栈,切换到之前显示的页面。
        finish();
    }
}